<template>
  <ConfirmModal
    title="修改登录密码"
    :show="show"
    :onConfirm="onConfirm"
    :onCancel="onCancel"
    :width="350"
    @update:show="onShow"
  >
    <FormMain
      ref="formMain"
      :list="formList"
      :data="formData"
      :layout="layout"
      :labelWidth="labelWidth"
    >
      <template #old_pwd="scope">
        <ElInput v-bind="scope" />
      </template>
      <template #new_pwd="scope">
        <ElInput v-bind="scope" />
      </template>
      <template #new_pwd_confirmation="scope">
        <ElInput v-bind="scope" />
      </template>
    </FormMain>
  </ConfirmModal>
</template>

<script lang="ts" setup>
import type { FormItemConfigList, FormMainInstance } from "@/components/form";
import { stringifyFormData, generateFormData } from "@/components/form";
import { getConfirmPasswordRule, passwordRule } from "@/utils";
import type { ChangePwdParams } from "@/api";
import { changePwd } from "@/api";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store";

const props = defineProps<{
  show: boolean;
}>();

const emits = defineEmits<(e: "update:show", value: boolean) => void>();

const userStore = useUserStore();

const formList: FormItemConfigList<
  ChangePwdParams & {
    new_pwd_confirmation: string;
  },
  {
    new_pwd_confirmation: never;
  }
> = [
  {
    key: "old_pwd",
    label: "原密码",
    props: {
      type: "password",
      showPassword: true,
      maxlength: 20,
    },
    extra: {
      isInput: true,
    },
    rules: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  },
  {
    key: "new_pwd",
    label: "新密码",
    props: {
      type: "password",
      showPassword: true,
      maxlength: 20,
    },
    extra: {
      isInput: true,
    },
    rules: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      passwordRule,
    ],
  },
  {
    key: "new_pwd_confirmation",
    label: "确认密码",
    props: {
      type: "password",
      showPassword: true,
      maxlength: 20,
    },
    extra: {
      isInput: true,
    },
    rules: [
      { required: true, message: "请输入确认密码", trigger: "blur" },
      getConfirmPasswordRule(() => formData.value.new_pwd),
    ],
    stringify: () => undefined,
  },
];

const layout = {
  span: 24,
};

const labelWidth = "80px";

const formMain = ref<FormMainInstance>();

const formData = ref(generateFormData(formList));

const onShow = (value: boolean) => {
  emits("update:show", value);
};

const onConfirm = () => {
  return formMain.value?.validate().then(async () => {
    console.log("confirm", stringifyFormData(formData.value, formList));

    await changePwd(stringifyFormData(formData.value, formList));

    ElMessage.success("密码修改成功");

    userStore.getInfo();
  });
};

const onCancel = () => {
  console.log("cancel");
};
watch(
  () => props.show,
  (n) => {
    if (!n) {
      formMain.value?.resetFields();
    }
  },
);
</script>
